<template>
  <div class="favorites-section">
    <h3>我的收藏</h3>
    <div class="favorites-list">
      <el-card v-for="item in favorites" :key="item.id" class="favorite-item">
        <el-image :src="item.image" class="favorite-image"></el-image>
        <div class="favorite-info">
          <h4>{{ item.name }}</h4>
          <p class="price">¥{{ item.price }}</p>
        </div>
        <div class="favorite-actions">
          <el-button type="primary" size="small" @click="viewDetail(item.id)">查看详情</el-button>
          <el-button type="danger" size="small" @click="removeFavorite(item.id)">取消收藏</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const favorites = ref([])
const user = ref(localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {})

const getFavorites = async () => {
  try {
    const res = await request.get('/favorite/list', { params: { userId: user.value.user.userId } })
    if (res.code === '0') {
      favorites.value = res.data
    } else {
      ElMessage.error(res.msg || '获取收藏列表失败')
    }
  } catch (error) {
    ElMessage.error('获取收藏列表失败')
  }
}

const removeFavorite = async (id) => {
  try {
    await ElMessageBox.confirm('确认取消收藏该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete(`/favorite/delete/${id}`)
    if (res.code === '0') {
      ElMessage.success('取消收藏成功')
      getFavorites()
    } else {
      ElMessage.error(res.msg || '取消收藏失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消收藏失败')
    }
  }
}

const viewDetail = (id) => {
  router.push({
    name: 'ProductDetail',
    params: { id }
  })
}

onMounted(() => {
  getFavorites()
})
</script>

<style scoped>
.favorites-section {
  padding: 20px;
}

.favorites-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.favorite-item {
  display: flex;
  flex-direction: column;
}

.favorite-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.favorite-info {
  padding: 10px 0;
}

.favorite-info h4 {
  margin: 0 0 10px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.favorite-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
}
</style> 